#!/bin/bash

# Default MySQL version
MYSQL_VERSION="8.0.25"

# Variables
DOWNLOAD_DIR="/tmp/mysql-download"
DATADIR="/var/lib/mysql"
install_dir=/usr/local/mysql
SOURCE_FILE=""
CURRDIR=$(pwd)
TCMALLOC_PREFIX=""  # 新增变量：用于存储 tcmalloc 的前缀参数
TCMALLOC_PAGESIZE=""  # 新增变量：用于存储 tcmalloc 的页大小参数

# Parse command-line options
while getopts ":v:s:d:t:p:u" opt; do  # 新增选项 -u
  case ${opt} in
    v )
      MYSQL_VERSION=$OPTARG
      ;;
    s )
      SOURCE_FILE=$OPTARG
      ;;
    d )
      DATADIR=$OPTARG  # 新增参数：指定数据目录
      ;;
    t )
      TCMALLOC_PREFIX="--prefix=$OPTARG"  # 新增参数：指定 tcmalloc 前缀
      ;;
    p )
      TCMALLOC_PAGESIZE="--with-tcmalloc-pagesize=$OPTARG"  # 新增参数：指定 tcmalloc 页大小
      ;;
    u )  # 新增选项：一键卸载
      echo "Uninstalling MySQL..."
      # 停止 MySQL 服务
      pkill -f "mysqld"
      # 删除安装目录
      sudo rm -rf ${install_dir}
      # 删除数据目录
      sudo rm -rf ${DATADIR}
      # 删除日志目录
      sudo rm -rf /var/log/mysql
      # 从 .bashrc 中移除路径配置
      sed -i "/export PATH=.*${install_dir}\/bin/d" ~/.bashrc
      echo "MySQL has been uninstalled successfully."
      exit 0
      ;;
    \? )
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    : )
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

# Check if -s option is provided and validate the source file
if [ -n "$SOURCE_FILE" ]; then
  if [[ ! "$SOURCE_FILE" =~ mysql-boost-${MYSQL_VERSION}\.tar\.gz$ ]]; then
    echo "Error: Source file must be in the format 'mysql-boost-${MYSQL_VERSION}.tar.gz'"
    exit 1
  fi
else
  SOURCE_FILE="mysql-boost-${MYSQL_VERSION}.tar.gz"
fi
SOURCE_DIR="/usr/local/src/mysql-${MYSQL_VERSION}"
rm -rf $SOURCE_DIR
mkdir -p $SOURCE_DIR

# Check if MySQL is already installed
if [ -d "/usr/local/mysql" ]; then
  echo "MySQL is already installed."
  exit 0
fi

# Remove any existing MySQL installations
rpm -qa | grep mysql | xargs -i{} rpm -e --nodeps {}
rpm -qa | grep mariadb | xargs -i{} rpm -e --nodeps {}
# 关闭防火墙。
systemctl stop firewalld.service
systemctl disable firewalld.service
# 关闭SELinux
setenforce 0
# 永久关闭SElinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux
# 关闭透明 hugepages
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag

# Step 1: Install dependencies

sudo yum install -y gcc gcc-c++ cmake ncurses ncurses-devel bison wget openssl-devel openssl git libtirpc libtirpc-devel readline readline-devel
if [ $? -ne 0 ]; then
  echo "Error: Failed to install dependencies."
  exit 1
fi
# 安装rpcgen,默认的os 系统中的源没有rpcgen，需要手动安装。
sudo yum install -y ./deps/rpcgen-1.4.2-1.ky10.aarch64.rpm

# Use the specified source file or download the default one
if [ -f "$SOURCE_FILE" ]; then
  echo "Using specified source file: $SOURCE_FILE"
else
  mkdir -p $DOWNLOAD_DIR
  cd $DOWNLOAD_DIR
  echo "Downloading MySQL source file..."
  wget https://dev.mysql.com/get/Downloads/MySQL-8.0/$SOURCE_FILE
  if [ $? -ne 0 ]; then
    echo "Error: Failed to download MySQL source file."
    exit 1
  fi
fi

tar -xzf $SOURCE_FILE
if [ $? -ne 0 ]; then
  echo "Error: Failed to extract MySQL source file."
  exit 1
fi

mv mysql-${MYSQL_VERSION}/* $SOURCE_DIR
if [ $? -ne 0 ]; then
  echo "Error: Failed to move MySQL source directory."
  exit 1
fi

# Step 3: Compile MySQL
cd $SOURCE_DIR
mkdir build
cd build
boost_dir="$(pwd)/../boost/$(ls ../boost/)"

cmake .. \
    -DBUILD_CONFIG=mysql_release \
    -DCMAKE_INSTALL_PREFIX=${install_dir} \
    -DMYSQL_DATADIR=${DATADIR} \
    -DWITH_BOOST=${boost_dir} \
    -DDEFAULT_CHARSET=utf8 \
    -DDEFAULT_COLLATION=utf8_general_ci \
    -DCMAKE_C_FLAGS="-march=armv8.2-a+crc+lse " \
    -DCMAKE_CXX_FLAGS="-march=armv8.2-a+crc+lse " \
    $TCMALLOC_PREFIX \
    $TCMALLOC_PAGESIZE
if [ $? -ne 0 ]; then
  echo "Error: CMake configuration failed."
  exit 1
fi

make -j$(nproc --all)
if [ $? -ne 0 ]; then
  echo "Error: Compilation failed."
  exit 1
fi

sudo make install
if [ $? -ne 0 ]; then
  echo "Error: Installation failed."
  exit 1
fi

# 创建mysql用户组。
groupadd mysql
# 创建mysql用户。
useradd -g mysql mysql

# 创建日志目录
sudo rm -rf  /var/log/mysql
sudo mkdir -p /var/log/mysql
sudo chown mysql:mysql /var/log/mysql
sudo chmod 755 /var/log/mysql

sudo cp ${CURRDIR}/my.cnf /etc/my.cnf
# Step 4: Initialize MySQL
sudo mkdir -p $DATADIR
sudo chown -R mysql:mysql $DATADIR
sudo ${install_dir}/bin/mysqld --initialize --user=mysql --basedir=${install_dir} --datadir=$DATADIR
if [ $? -ne 0 ]; then
  echo "Error: MySQL initialization failed."
  exit 1
fi



# Step 5: Start MySQL service
${install_dir}/bin/mysqld --defaults-file=/etc/my.cnf &
if [ $? -ne 0 ]; then
  echo "Error: Failed to start MySQL service."
  exit 1
fi

sleep 5
mysq_alive=1
until [ ${mysq_alive} -eq 0 ]
do
  sleep 1
  lsof -i :3306
  mysq_alive=$?
done

# Step 6: Modify password
temporary_password=`grep "temporary password" /var/log/mysql/mysqld.log |awk '{print $13}'`
${install_dir}/bin/mysql -uroot -p$temporary_password --connect-expired-password -e "alter user 'root'@'localhost' identified by '123456';create user 'root'@'%' identified by '123456';grant all privileges on *.* to 'root'@'%';flush privileges;"
if [ $? -ne 0 ]; then
  echo "Error: Failed to modify MySQL root password."
  exit 1
fi

# 添加 ${install_dir}/bin 到 PATH 环境变量
if ! grep -q "${install_dir}/bin" ~/.bashrc; then
  echo "export PATH=\${PATH}:${install_dir}/bin" >> ~/.bashrc
  source ~/.bashrc
fi

printf "MySQL installation completed successfully.\n root password: 123456 \n Please check the log file for more details: /var/log/mysql/mysqld.log"
